//    Copyright (C) Kherty.  All rights reserved.
using System;

namespace OpenLS.Spreadsheet
{
    public static class DateTimeConverter
    {
        public static DateTime DoubleToDateTime(double d, DateTimeOrigin origin)
        {
            switch (origin)
            {
                case
                    DateTimeOrigin.Origin1900:
                    if (d < 60)
                    {
                        return FirstDate1900.AddDays(d + 1);
                    }
                    return FirstDate1900.AddDays(d);
                case DateTimeOrigin.Origin1904:
                    return FirstDate1904.AddDays(d);
                default:
                    throw new NotSupportedException();
            }
        }

        public static bool IsValidDouble (double d)
        {
            return d >=0 && d <= maxDouble;
        }
        public const double maxDouble = 100000;//\\
        public static double DateTimeToDouble(DateTime d, DateTimeOrigin origin)
        {
            switch (origin)
            {
                case DateTimeOrigin.Origin1900:
                    {
                        TimeSpan ts = (d - FirstDate1900);

                        double result;
                        /*result = ts.TotalDays + ((double) ts.Hours)/24 + ((double) ts.Minutes)/24/60 +
                                        ((double) ts.Seconds)/24/60/60 + ((double) ts.Milliseconds)/24/60/60/1000;*/
                        result = ts.TotalDays;
                        if (result < 60)
                            result--;
                        return result;
                    }
                case DateTimeOrigin.Origin1904:
                    {
                        TimeSpan ts = (d - FirstDate1904);
                        return ts.TotalDays;

                    }
                    default: throw new NotSupportedException();

            }
        }
        static readonly DateTime FirstDate1900 = new DateTime(1899, 12, 30); 
        static readonly DateTime FirstDate1904 = new DateTime(1904, 1, 1); 
    }
}
